package util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import util.MyLocation.LocationResult;
import voice.main.ApplicationsActivity;
import voice.main.ContactsActivity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.provider.AlarmClock;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;

public class TaskHelper {
	public static boolean isNumeric(String str) {
	  return str.matches("-?\\d+(\\.\\d+)?");
	}
	
	public static void startCall(Context context, String data) {
		if (isNumeric(data) || data.isEmpty()) startCallByNumber(context, data);
		else startCallByContactName(context, data);
	}
	
	public static void startCallByNumber(Context context, String number) {
		Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setData(Uri.parse("tel:" + number.trim()));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void startCallByContactName(Context context, String contactName) {
		HashMap<String,String> contactList;
    	contactList = TaskHelper.findContact(context, contactName);
    	if (contactList.size() > 1) {
        	Intent intent = new Intent(context, ContactsActivity.class);
        	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        	intent.putExtra("CONTACTS_LIST", contactList);
        	intent.putExtra("MODE", ContactsActivity.CALL_MODE);
        	context.startActivity(intent);
    	}
    	else for (Map.Entry<String, String> entry : contactList.entrySet()) {
            String number = entry.getValue();
            TaskHelper.startCallByNumber(context, number);
        }
	}
	
	public static HashMap<String,String> findContact(Context context, String displayName) {
        Cursor phoneCursor = null;
        HashMap<String,String> contactList = new HashMap<String,String>();
        ContentResolver contentResolver = context.getContentResolver();
		try {
			Uri uContactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
			String strProjection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
         
			phoneCursor = contentResolver.query(uContactsUri, null, null, null, strProjection);
			phoneCursor.moveToFirst();
	
			String name = "";
			String phoneNumber = "";

			int nameColumn = phoneCursor.getColumnIndex(Phone.DISPLAY_NAME);
			int phoneColumn = phoneCursor.getColumnIndex(Phone.NUMBER);

			while(!phoneCursor.isAfterLast()) {
				name = phoneCursor.getString(nameColumn);
				phoneNumber = phoneCursor.getString(phoneColumn);
				if (name.contains(displayName)) {
					contactList.put(name, phoneNumber);
				}
				phoneCursor.moveToNext();
			}
       }
       catch(Exception e) {
       }
       finally {
    	   if(phoneCursor != null) {
             phoneCursor.close();
             phoneCursor = null;
          }
       }
		return contactList;
	}
	
	public static void sendSMS(Context context, String data) {
		if (isNumeric(data) || data.isEmpty()) sendSMSByNumber(context, data);
		else sendSMSByContactName(context, data);
	}
	
	public static void sendSMSByNumber(Context context, String number)
	{
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse("sms:" + number.trim()));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void sendSMSByContactName(Context context, String contactName)
	{
		HashMap<String,String> contactList;
    	contactList = TaskHelper.findContact(context, contactName);
    	if (contactList.size() > 1) {
        	Intent intent = new Intent(context, ContactsActivity.class);
        	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        	intent.putExtra("CONTACTS_LIST", contactList);
        	intent.putExtra("MODE", ContactsActivity.SMS_MODE);
        	context.startActivity(intent);
    	}
    	else for (Map.Entry<String, String> entry : contactList.entrySet()) {
            String number = entry.getValue();
            TaskHelper.sendSMSByNumber(context, number);
        }
	}
	
	public static void setAlarm(Context context, int hour, int minute) {
    	Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM); 
    	intent.putExtra(AlarmClock.EXTRA_MESSAGE, "New Alarm"); 
    	intent.putExtra(AlarmClock.EXTRA_HOUR, hour); 
    	intent.putExtra(AlarmClock.EXTRA_MINUTES, minute); 
    	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	context.startActivity(intent);
	}
	
	public static void searchAddress(Context context, String address) {
		Uri uri = Uri.parse("geo:0,0?q="+ address);
    	Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	context.startActivity(intent);
	}
	
	public static void getCurrentLocation(final Context context) {
		LocationResult locationResult = new LocationResult(){
    	    @Override
    	    public void gotLocation(Location location){
    			Uri uri = Uri.parse("geo:"+ location.getLatitude() + "," + location.getLongitude()+ "?z=18");
    	    	Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    	    	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	    	context.startActivity(intent);
    	    }
    	};
    	MyLocation myLocation = new MyLocation();
    	myLocation.getLocation(context, locationResult);
	}
	
	public static void openCallWithSkype(Context context,String user_name) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setData(Uri.parse("skype:" + user_name));
		context.startActivity(intent);
	}
	
	public static void sendMailToAddress(Context context, String email_address) {
	    Intent intent = new Intent(android.content.Intent.ACTION_SEND);  
	    String emailList[] = { email_address };
	    intent.putExtra(android.content.Intent.EXTRA_EMAIL, emailList);  
	    intent.setType("plain/text"); 
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent); 
	}
	
	public static void openFacebook(Context context) {
		try {
			Intent intent = new Intent("android.intent.category.LAUNCHER");
			intent.setClassName("com.facebook.katana", "com.facebook.katana.LoginActivity");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		}
		catch (ActivityNotFoundException anfe) {
			Intent goToMarket = new Intent(Intent.ACTION_VIEW);
			goToMarket.setData(Uri.parse("market://details?id=com.facebook.katana"));
			goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(goToMarket);
		}
	}
	
	public static void openWebBrowser(Context context) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_LAUNCHER); 
		intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity"); 
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void toggleWifi(Context context) {
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
		if (wifiManager.isWifiEnabled()) 
		{
			wifiManager.setWifiEnabled(false);
			Toast toast = Toast.makeText(context, "Wifi turned off.", Toast.LENGTH_SHORT);
			toast.show();
		}
		else 
		{
			wifiManager.setWifiEnabled(true);
			Toast toast = Toast.makeText(context, "Wifi turned on.", Toast.LENGTH_SHORT);
			toast.show();
		}
	}
	
	public static void toggle3G(Context context)
	{
		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		int type = telephonyManager.getNetworkType();

		if ((type == TelephonyManager.NETWORK_TYPE_HSDPA
		    || type == TelephonyManager.NETWORK_TYPE_HSPA
		    || type == TelephonyManager.NETWORK_TYPE_HSUPA
		    || type == TelephonyManager.NETWORK_TYPE_UMTS
		    || type == TelephonyManager.NETWORK_TYPE_EVDO_0
		    || type == TelephonyManager.NETWORK_TYPE_EVDO_A) && (telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)) {

			if (toggle3G(context, false))
			{
				Toast toast = Toast.makeText(context, "3G connection turned off.", Toast.LENGTH_SHORT);
				toast.show();
			}
		}
		else {

			if (toggle3G(context, true))
			{
				Toast toast = Toast.makeText(context, "3G connection turned on.", Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}
	
	private static boolean toggle3G(Context context, boolean enabled )
	{
		try 
		{
			final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		    Class conmanClass;
			conmanClass = Class.forName(conman.getClass().getName());
		    final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
		    iConnectivityManagerField.setAccessible(true);
		    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
		    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
		    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
		    setMobileDataEnabledMethod.setAccessible(true);
		    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
		} 
		catch (Exception e) {
			Toast toast = Toast.makeText(context, "Error turning 3G on/off.", Toast.LENGTH_SHORT);
			toast.show();
			return false;
		} 
		return true;
	}
	
	public static void toggleBluetooth(Context context)
	{
		BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
	    if (bluetoothAdapter.isEnabled()) {
	    	bluetoothAdapter.disable(); 
	    	Toast toast = Toast.makeText(context, "Bluetooth connection turned off.", Toast.LENGTH_SHORT);
			toast.show();
	    }
	    else { 
	    	bluetoothAdapter.enable(); 
	    	Toast toast = Toast.makeText(context, "Bluetooth connection turned on.", Toast.LENGTH_SHORT);
			toast.show();
	    } 
	}
	
	public static void openCamera(Context context)
	{
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void openVideoCamera(Context context)
	{
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void openSoundRecorder(Context context)
	{
		Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void openVideoPlayer(Context context)
	{
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setType("video/*");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void openMusicPlayer(Context context)
	{
		Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void openImageViewer(Context context)
	{
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void openApplications(Context context, String appName)
	{
		final PackageManager pm = context.getPackageManager();
	    List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
		if (appName == "")
		{
		    ArrayList<String> apps = new ArrayList<String>();
		    for (ApplicationInfo packageInfo : packages) {
		    	apps.add(packageInfo.loadLabel(pm).toString());
		    }
		    Intent intent = new Intent(context, ApplicationsActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putStringArrayListExtra("APPS_LIST", apps);
			context.startActivity(intent);
		}
		else 
		{
			for (ApplicationInfo packageInfo : packages) {
		    	if (appName.equals(packageInfo.loadLabel(pm).toString()))
		    	{
					Intent intent = pm.getLaunchIntentForPackage(packageInfo.packageName);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent);
		    	}
		    }
		}
	}
	
	public static boolean isNetworkConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni == null)
			return false;
		else
			return true;
	}	
}
